package cn.myspringboot.user.config;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //从请求中获取token
        String token = request.getHeader("token");
        //判断是否有token
        if (token != null) {
           try {
               //有 就解析token  并且放行
               JwtUtil.parseJwtToken(token);
               Long userId = JwtUtil.getUserIdFromToken(token);
               request.setAttribute("userId",userId);
               return true;
           }catch (Exception e) {
               //有异常就阻拦
               response.setContentType("application/json;charset=UTF-8");
               response.getWriter().println("{\"success\":false,\"code\":600,\"message\":\"toLogin\"}");
               return false;
           }
        } else {
            //没有token 就阻拦
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().println("{\"success\":false,\"code\":600,\"message\":\"toLogin\"}");
            return false;
        }
    }
}
